package com.handydata.antifraud.port.impl;

import com.bstek.urule.runtime.KnowledgePackage;
import com.bstek.urule.runtime.KnowledgeSession;
import com.bstek.urule.runtime.KnowledgeSessionFactory;
import com.handydata.antifraud.common.exception.RuleNotFoundException;
import com.handydata.antifraud.entity.RiskRuleDictIinfoDao;
import com.handydata.antifraud.port.RuleEngineInvokers;
import com.handydata.antifraud.port.SendKnowledgePackage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.function.Consumer;

@Service
public class RuleEngineInvokersImpl implements RuleEngineInvokers {

    @Autowired
    private SendKnowledgePackage sendKnowledgePackage;

    private String processName;

    private KnowledgePackage knowledgePackage;

    @Override
    public <R> void invokeDecision(Consumer<KnowledgeSession> consumer) throws RuleNotFoundException {
        Objects.requireNonNull(consumer);
        KnowledgeSession session = KnowledgeSessionFactory.newKnowledgeSession(knowledgePackage);
        consumer.accept(session);
        session.startProcess(processName);
    }

    @Override
    public void refreshPackage(String packageName) {
        sendKnowledgePackage.getKnowledgePackage(packageName);
    }

    @Override
    public RiskRuleDictIinfoDao ruleEngineInvoker(String packageName, String processName) {
        this.processName = processName;
        this.knowledgePackage = sendKnowledgePackage.getKnowledgePackage(packageName);
        return new RiskRuleDictIinfoDao(packageName);
    }


}
